import {
  reactive,
  ref,
  watch,
  computed,
  watchEffect,
  getCurrentInstance,
} from "@vue/composition-api";
import sleep from '@/utils/sleep'

import {
  useConst,
  usePage,
  useSearch
} from "@/hooks/crud";

import svs_sys_dic from "@/service/sys/dic"


/* 树过滤功能 hook */
function useTeeFilter(tree) {
  const treeFilterText = ref("");

  watch(treeFilterText, (val) => {
    tree.value.filter(val);
  });

  const filterNode = (value, data) => {
    if (!value) return true;
    return data.label.indexOf(value) !== -1;
  };
  return {
    treeFilterText,
    filterNode,
  };
}

/* 树相关功能入口 hook */
function useTree(that) {
  const tree = ref(null);
  const filterFun = useTeeFilter(tree);
  const treeLoading = ref(true);
  const treeData = ref([
    // {
    //   label: "分组一",
    //   children: [
    //     { label: "节点1" },
    //   ],
    // },
  ]);
  watch(treeData, (val) => {
    treeLoading.value = true;
    setTimeout(() => {
      treeLoading.value = false;
    }, 300);
  });

  const treeProps = reactive({
    label: "label",
    children: "children",
  });


  const nodeClick = (item) => {
    // console.log(item);
    if (item.value != "all") {
      that.$emit('tree-node-click', item.value)
    }
  };

  const treeHeight = computed(() => {
    return window.hei.value - 234 + "px";
  });
  return {
    tree,
    nodeClick,
    treeProps,
    treeData,
    ...filterFun,
    treeHeight,
    treeLoading,

  };
}

/* 从后台获取的菜单列表，转化成tree data */
function menuListToTreeData(menuList) {
  return [{
    label: "全部菜单",
    value: "all",
    children: menuList.map((item) => {
      return {
        label: item.cname + `[${item.ename}]`,
        value: item.id,
      };
    }),
  }, ];
}

/* 获取列表的功能 */
function useGetList({
  root
}) {
  const data = reactive({
    rows: [],
    count: 0
  });
  const getList = (page, condition = {}) => {
    // console.log(condition);
    return svs_sys_dic.getSearchData({
      page: [page.size, page.offset],
      menu_id: condition.menu_id
    }).then(res => {
      console.log(res);
      data.rows = res.rows;
      data.count = res.count;
      page.total = res.count;
      // console.log(page);
    })
  };
  return [data, getList];
}

function useGetGroupList({
  root
}, treeData) {
  const groupList = ref([]);
  watch(groupList, (val) => {
    treeData.value = menuListToTreeData(val);
  });
  const getList = () => {
    svs_sys_dic.getDicList().then(res => {
      console.log(res);
      groupList.value = res;

    })
  };

  getList();
  return [groupList, getList];
}

function useSetCrudOption(option, groupList) {
  option.table.column = [{
      label: "菜单",
      prop: "menu_id",
      form: {
        index: -2,
        editDisabled: false,
        component: "el-select",
        componentProps: {
          filterable: true,
        },
        rules: [{
          required: true,
          message: "必须项",
          trigger: "blur"
        }],
        options: {
          list: [],
          label: "cname",
          valueKey: "id",
          valueField: "id",
        },
      },
    },

    {
      label: "文本",
      prop: "label",
      form: {
        componentProps: {
          placeholder: "请输入选项的显示内容",
        },
        editDisabled: false,
        rules: [{
          required: true,
          message: "必须项",
          trigger: "blur"
        }],
        newRow: true,
      },
    },
    {
      label: "对应值",
      prop: "value",
      form: {
        componentProps: {
          placeholder: "请输入选项的值",
        },
        editDisabled: false,
        rules: [{
          required: true,
          message: "必须项",
          trigger: "blur"
        }],
      },
    },
    {
      label: "排序",
      prop: "orders",
      form: {
        editDisabled: false,
        span: 8,
        component: "el-input-number",
        componentProps: {
          min: 0,
          max: 100,
        },
      },
    },
    {
      label: "值可修改",
      prop: "is_edit",
      // hiden: true,
      form: {
        index: -1,
        editDisabled: false,
        span: 8,
        component: "el-switch",
        labelWidth: "80px",
        componentProps: {
          activeValue: true,
          inactiveValue: false,
        },
        options: {
          list: [{
              label: "是",
              value: true
            },
            {
              label: "否",
              value: false
            },
          ],
          label: "label",
          valueKey: "value",
        },
      },
    },
  ];

  option.form.menu = {
    display: true,
  };
  /* 将后台获取的grouplist添加给option */
  watch(groupList, (val) => {
    console.log(val);
    option.table.column[0].form.options.list = val;
  });
}

/* 添加菜单的功能，包括popover相关的 */
function useAddMenu({
  root
}) {
  const addMenucNameModel = ref("");
  const addMenueNameModel = ref("");
  const addMenuVisiable = ref(false);
  const addMenuPopoverErrorMsg = ref(false);
  const setAddMenuVisiable = (bool) => {
    addMenuVisiable.value = bool;
  };
  const saveAddMenu = () => {
    if (addMenucNameModel.value === "" || addMenueNameModel.value === "") {
      addMenuPopoverErrorMsg.value = true;
      return;
    }
    addMenuPopoverErrorMsg.value = false;


    svs_sys_dic.AddOneDic({
      ename: addMenueNameModel.value,
      cname: addMenucNameModel.value,
    }).then(res => {
      console.log(res);
      if (res.insertRows === 1) {
        root.$message.success("添加成功");
        setAddMenuVisiable(false);
      } else {
        root.$message.error("添加失败");
      }
    }).catch((error) => {
      console.log(error);
    });
  };
  return {
    addMenucNameModel,
    addMenueNameModel,
    addMenuVisiable,
    setAddMenuVisiable,
    addMenuPopoverErrorMsg,

    saveAddMenu,
  };
}

/* 菜单项的 新增、修改的功能 */
function useAddUpdate({
  root
}, that) {
  const add = (data, loading, done) => {
    console.log(data);
    // loading();
    if (!data.is_edit) {
      data.is_edit = false;
    }
    // return;

    svs_sys_dic.post(data).then(res => {
      console.log(res);
      if (res.id > 0) {
        root.$message.success("新增成功");
        done();
        that.$emit('refresh');
      } else {
        root.$message.warning("新增失败或该菜单已有对应值");
      }
    }).catch(error => {
      console.error(error);
      root.$message.error("操作出现错误");
    })

    loading();
  };

  /* 修改api */
  const rowEditSubmit = (data, loading, done) => {
    console.log(data);
    if (!data.id) return false;

    const sendData = {
      label: data.label,
      value: data.value,
      menu_id: data.menu_id,
      orders: data.orders,
      is_edit: data.is_edit,
    };

    svs_sys_dic.put(data.id, sendData).then(res => {
      console.log(res);
      if (res.affectedRows == 1) {
        root.$message.success("修改成功");
        loading();
        done()
        that.$emit('refresh');
      } else {
        loading();
        root.$message.error("修改失败");
      }
    }).catch(error => {
      console.log(error);
      root.$message.error("操作失败");
      loading();
    })

    // root.$axios
    //   .send(config)
    //   .then((res) => {
    //     // console.log(res);
    //     if (res.status === 200 && res.data.update_state) {
    //       root.$message.success("修改成功");
    //     } else {
    //       root.$message.error("修改失败");
    //     }
    //     loading();
    //   })
    //   .catch((error) => {
    //     console.log(error);
    //     root.$message.error("操作失败");
    //     loading();
    //   });
  };

  /* 行删除 api */
  const rowDelApi = (id = 0) => {
    // console.log(id);
    // return;

    if (id > 0) {
      svs_sys_dic.delete(id).then(res => {
        console.log(res);
        if (res.affectedRows === 1) {
          root.$message.success("删除成功！")
          that.$emit('refresh');
        } else {
          root.$message.error("删除失败！")
        }
      })
    }
  };

  /* 行删除 按钮 */
  const rowDel = (scope) => {
    const {
      row
    } = scope;
    // console.log(row);
    // if (row.is_edit == false) {
    //   root.$message.error("不能删除不可编辑的项！");
    //   return;
    // }
    if (row.menu_id == 0) {
      root.$message.warning("下拉菜单暂不能自行删除");
      root.$message.warning("下拉菜单删除将删除其下的所有选项");
    } else {
      root
        .$confirm(
          `确定要删除行号为${scope.$index + 1}的数据吗？（该操作无法恢复）`,
          "请确认", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
        .then(() => {
          // root.$message.success("此处执行删除操作");
          rowDelApi(row.id);
        })
        .catch(() => {
          //this.$message({
          //type: 'info',
          //message: '已取消删除'
          //});
        });
    }
  };

  return {
    addSubmit: add,
    rowEditSubmit,
    rowDel,
  };
}

function useCrudVars(props, ctx, that, treeData) {
  const [groupList, getGroupList] = useGetGroupList(ctx, treeData);
  /* 树刷新click */
  const treeListRefresh = () => {
    getGroupList();
  };
  const crudVars = useConst(props, ctx, 260);
  useSetCrudOption(crudVars.option, groupList);
  const refresh = () => {
    crudVars.loading.value = true;
    // getGroupList();
    return crudGetList(pages.page, searchs.condition.value).then(async (res) => {
      await sleep(200)
      crudVars.loading.value = false;
    });
  };

  // 树点击事件触发。刷新get list
  that.$on('tree-node-click', (menu_id) => {
    searchs.condition.value = {
      menu_id
    };
    refresh();
  })
  // 提供一个刷新事件监听。
  that.$on('refresh', () => {
    refresh();
  })
  const [crudData, crudGetList] = useGetList(ctx);
  const pages = usePage(refresh);

  const searchFormat = (formData) => {
    const condition = {};

    return condition;
  };
  const searchs = useSearch(pages.page, searchFormat, refresh);

  const addUpdates = useAddUpdate(ctx, that);

  /*行编辑时 打开dialog前的钩子 操作*/
  const beforeOpenDialog = (type, done, rowscope) => {
    // console.log(type);
    // return;
    const col = crudVars.option.table.column;
    /* 编辑时 */
    if (type === 1) {
      if (rowscope.row.is_edit == "0") {
        const disabledList = ["value", "menu_id", "is_edit"];
        col.forEach((item) => {
          disabledList.includes(item.prop) && (item.form.editDisabled = true);
        });
        // crudVars.option.form.menu.display = false;
      } else {
        col.forEach((item) => {
          item.form.editDisabled = false;
        });
        crudVars.option.form.menu.display = true;
      }
    } else if (type === 0) {
      //新增时
      col.forEach((item) => {
        item.form.editDisabled = false;
      });
      crudVars.option.form.menu.display = true;
    }
    done();
  };

  const onRowDblclick = () => {
    crudVars.crud.value.openEditRow()
  }

  refresh();
  return {
    crudOption: crudVars.option,
    crud: crudVars.crud,
    loading: crudVars.loading,
    ...pages,
    crudData,
    ...addUpdates,
    refresh,
    ...searchs,
    crudGetList,
    treeListRefresh,
    beforeOpenDialog,
    onRowDblclick,
  };
}

/* 组件入口setup hook */
function useEnter(props, ctx) {
  const that = getCurrentInstance();
  const trees = useTree(that);
  const cruds = useCrudVars(props, ctx, that, trees.treeData);

  const addMenus = useAddMenu(ctx);


  return {
    ...trees,
    ...cruds,
    ...addMenus,
  };
}

export default {
  name: "sys-dic",
  components: {},
  props: {},
  setup(props, ctx) {
    return useEnter(props, ctx);
  },
};
